<template>
  <el-dialog
    :before-close="handleClose"
    :title="title"
    :visible.sync="isOpen"
    width="1800px"
    :close-on-click-modal="false"
    append-to-body
  >
    <el-form
      :model="form"
      :label-position="dialogFormLabelPosition"
      :rules="dialogRules"
      ref="formRef"
      label-width="100px"
    >
      <el-row :gutter="20">
        <el-col :span="24">
          <el-form-item label="策略名称" prop="trafficRuleName">
            <el-input
              :disabled="isOnlyView"
              v-model="form.trafficRuleName"
              style="width: 300px"
              placeholder="请输入策略名称"
              clearable
            />
          </el-form-item>
          <el-form-item label="时间段" prop="time">
            <el-tabs
              type="border-card"
              v-model="activeName"
              @tab-click="handleClick"
              style="width: 100%"
            >
              <el-tab-pane label="工作日" name="first">
                <ListTable1 ref="ListTableRef1" />
              </el-tab-pane>
              <el-tab-pane label="休息日" name="second">
                <ListTable2 ref="ListTableRef2" />
              </el-tab-pane>
              <el-tab-pane label="特殊类型" name="third">
                <ListTable3 ref="ListTableRef3" />
              </el-tab-pane>
            </el-tabs>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="ok(formRef)" :disabled="isOnlyView">确 定</el-button>
        <el-button plain @click="handleClose">取 消</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script>
import {
  addPassStrategyApi,
  queryTrafficRuleDetails
} from "@/api/intelligent";
import { parseTime } from "@/utils/ruoyi";
import ListTable1 from "./ListTable1";
import ListTable2 from "./ListTable2";
import ListTable3 from "./ListTable3";
import {commonConfiguration} from "@/views/intelligent/sub/accessStrategy/sub/dialog/common-configuration";


export default {
  components:{
    ListTable1,
    ListTable2,
    ListTable3,
  },

  data () {
    return {
      isOnlyView: commonConfiguration.isOnlyView,

      isOpen:false,
      title:'',
      form: {
        trafficRuleName: "",
        areaId: undefined,
        deviceIds: undefined,
      },
      trafficRuleId:'',
      activeName:'first',
      formRef:'',
      dialogFormLabelPosition:'right',
      dialogRules:{
        trafficRuleName: [
          { required: true, message: "必须填入策略名称", trigger: "blur" },
          {
            min: 2,
            max: 64,
            message: "设备名称长度必须介于 2 和 64 之间",
            trigger: "blur",
          },
        ],
        areaId: [{ required: true, message: "必须选择区域", trigger: "blur" }],
      },
    }
  },
  methods: {
    reset () {
      this.form.trafficRuleName = "";
      // this.form.areaId = [];
      // this.form.deviceIds = [];
    },
    // 弹窗关闭处理方法 && 取消
    handleClose () {
      // console.log(this.isOpen)
      // isOpen.value = !isOpen.value;
      this.isOpen = false;
      this.reset();
      // console.log('ssss')
    },

    handleClick (tab, event){},

    open(type, arr) {
      this.isOpen = true;
      this.title = type;
      if (type == "添加") {
          this.reset()
      } else {
        // console.log(arr,'arr')
        this.form.trafficRuleName = arr.strategy_name;
        // let areaIds = [];
        // let deviceIds = [];
        // console.log('arr',arr)
        // debugger
        // arr.areaInfo.forEach((item, index) => {
        //   areaIds.push(item.areaId);
        // });
        // arr.deviceInfo.forEach((item, index) => {
        //   deviceIds.push(item.deviceId);
        // });
        // console.log('deviceIds', deviceIds);
        // this.form.areaId = areaIds;
        // this.form.deviceIds = deviceIds;
        this.trafficRuleId = arr.strategy_id;
        this.getDetails(type, arr);
      }
    },

    //查询详细数据
    getDetails (type, arr) {
      // console.log('detail')
      // queryTrafficRuleDetails({
      //   trafficRuleId: id,
      //   trafficRuleType: "",
      // }).then((res) => {
        // console.log('res',res)
        this.$nextTick(() => {
          this.$refs.ListTableRef1.init(arr.strategy_list, type);
          this.$refs.ListTableRef2.init(arr.strategy_list, type);
          this.$refs.ListTableRef3.init(arr.strategy_list, type);
        });
      // });
    },

    //通行方式数组排序
    convertTrafficType (data) {
      let arr = [];
      data.forEach((item, index) => {
        arr.push(item.sort().join(""));
      });
      // console.log('通行方式数组排序arr', arr)
      return arr;
    },

    //表单提交
    async ok () {
      this.$refs.formRef.validate((validate)=>{
        if(validate){
          let result1 = [...this.$refs.ListTableRef1.submitForm().list];
          let result2 = [...this.$refs.ListTableRef2.submitForm().list];
          let result3 = [...this.$refs.ListTableRef3.submitForm().list];
          let finnal_result = result1.concat(result2).concat(result3);
          //请求参数
          let params = {
            trafficRuleName: this.form.trafficRuleName,
            areaIdList: this.form.areaId,
            deviceIdList: this.form.deviceIds,
            trafficRuleId: this.trafficRuleId ?? "",
            trafficRuleDetailsVoList: [],
          };
          if (this.title == "添加") {
            finnal_result.forEach((e, i) => {
              //添加工作日、节假日类型的数据
              if (e.trafficRuleType != 3) {
                params.trafficRuleDetailsVoList.push({
                  startTime: parseTime(e.timeArray[0]).slice(10, 19).trim(),
                  endTime: parseTime(e.timeArray[1]).slice(10, 19).trim(),
                  trafficRuleType: e.trafficRuleType,
                  doorLock: e.doorLock,
                  trafficType: this.convertTrafficType(e.trafficTypeArray).toString(),
                });
              } else {
                //添加特殊类型的数据
                console.log(
                  "e.timeArray[0]-第三种",
                  parseTime(e.timeArray[0]).trim()
                );
                params.trafficRuleDetailsVoList.push({
                  startTime: parseTime(e.timeArray[0]).trim(),
                  endTime: parseTime(e.timeArray[1]).trim(),
                  trafficRuleType: e.trafficRuleType,
                  doorLock: e.doorLock,
                  trafficType: this.convertTrafficType(e.trafficTypeArray).toString(),
                });
              }
            });
            //空的处理
            if (params.trafficRuleDetailsVoList.length !== 0) {
              let inspectArr = []; //检查数组
              let empty_count = 0; //数组里面含有空数组的个数
              let inspect_door_lock_array = []; //检查门锁权限的数组
              params.trafficRuleDetailsVoList.forEach((e, i) => {
                console.log("e", e);
                inspectArr.push(e.trafficType.split(","));
                inspect_door_lock_array.push(e.doorLock);
              });
              // console.log('inspect_door_lock_array', inspect_door_lock_array)
              // console.log('inspectArr',inspectArr)
              inspectArr.forEach((e, i) => {
                if (e.length == 0 || e.includes("")) {
                  empty_count++;
                }
              });
              inspect_door_lock_array.forEach((e, i) => {
                // console.log('e',e=='',)
                if (e == "") {
                  empty_count++;
                }
              });
              if (empty_count == 0) {
                console.log("正确的-检查完毕");
                addPassStrategyApi(params).then((res) => {
                  this.$message.success("添加成功");
                  this.isOpen = !(this.isOpen);
                  this.reset();
                  this.$emit("getList");
                });
              } else {
                console.log("1-请确保所有定时计划、门锁权限、通行方式 都填写完整");
                this.$message.warning(
                  "请确保所有定时计划、门锁权限、通行方式 都填写完整 !"
                );
                return false;
              }
            } else {
              console.log("2-请确保所有定时计划、门锁权限、通行方式 都填写完整");
              this.$message.warning(
                "请确保所有定时计划、门锁权限、通行方式 都填写完整 !"
              );
              return false;
            }
            window.location.reload()
          } else {
            finnal_result.forEach((e, i) => {
              // console.log('item', e)
              //编辑工作日、节假日类型的数据
              if (e.trafficRuleType != 3) {
                params.trafficRuleDetailsVoList.push({
                  //注意：toString()防止报[slice is not a function]的错
                  startTime: e.timeArray[0].toString().slice(15, 24).trim(),
                  endTime: e.timeArray[1].toString().slice(15, 24).trim(),
                  trafficRuleType: e.trafficRuleType,
                  doorLock: e.doorLock,
                  trafficType: this.convertTrafficType(e.trafficTypeArray).toString(),
                });
              } else {
                //编辑特殊类型的数据
                // console.log(parseTime(e.timeArray[0]), '编辑特殊类型的数据');
                // console.log(parseTime(e.timeArray[1]), '编辑特殊类型的数据');
                // return false
                params.trafficRuleDetailsVoList.push({
                  //注意：toString()防止报[slice is not a function]的错
                  startTime: parseTime(e.timeArray[0]).trim(),
                  endTime: parseTime(e.timeArray[1]).trim(),
                  trafficRuleType: e.trafficRuleType,
                  doorLock: e.doorLock,
                  trafficType: this.convertTrafficType(e.trafficTypeArray).toString(),
                });
              }
            });
            console.log(params, "修改发提交前");
            //空的处理（编辑数据）
            let empty_count_edit = 0;
            params.trafficRuleDetailsVoList.forEach((item, index) => {
              if (
                item.trafficType.split(",").length == 0 ||
                item.trafficType.split(",").includes("") ||
                item.doorLock == ""
              ) {
                empty_count_edit++;
              }
            });
            if (empty_count_edit == 0) {
              console.log("编辑检查通过！");
              addPassStrategyApi(params).then((res) => {
                this.$message.success("修改成功");
                this.isOpen = !(this.isOpen);
                this.reset();
                this.emit("getList");
              });
            } else {
              console.log("3-请确保所有定时计划、门锁权限、通行方式 都填写完整");
              this.$message.warning(
                "请确保所有定时计划、门锁权限、通行方式 都填写完整 !"
              );
            }
            // return false
            window.location.reload()
          }
        }else {
          console.log("4-请确保所有定时计划、门锁权限、通行方式 都填写完整");
          this.$message.warning(
            "请确保所有定时计划、门锁权限、通行方式 都填写完整 !"
          );
          console.log("error submitForm", 'fields');
        }
      })
    }
  },
  // watch:{
  //   'form.areaId':(n, o) => {
  //       console.log("new-val", n);
  //       if (n.length == 0) {
  //         // console.log('新',n.length)
  //         form.deviceIds = [];
  //       }
  //     }
  // }
}
</script>
